from fastapi import Request

from service import UserService, SongService
from common.result.Result import Result
from common.enum import BaseEnum
from util.log import Log
from util.str import Str
from util.token import Token


async def GetSongListByKeyword(req: Request, keyword: str, type: str):
    try:
        if Str.isBlank(keyword.strip(), type):
            return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)

        token = req.headers.get("token")

        user = await UserService.getUserByToken(token)
        
        # 通过 keyword 和 type 获取 song 列表
        songList = await SongService.getSongListByType(keyword, type)
        res = [dict(song) for song in songList]
        for song in res:
            song.update(isFavorite=False)

        if user != None:
            # 获取收藏信息
            songIdList = [item.id for item in songList]
            favoriteList = await SongService.getSongFavoriteList(songIdList, user.id)
            # 构造 收藏信息
            for song in res:
                for favorite in favoriteList:
                    if favorite.song_id == song.get("id"):
                        song.update(isFavorite=True)
            
        # 记录搜索历史
        if user != None:
            await SongService.updateSearchHistoryByUserId(keyword, user.id)

        return Result.success(res)
    except Exception as e:
        Log.error('获取 song 搜索历史异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)



